package io.bdmc.modules.sys.service.impl;

import io.bdmc.common.utils.Constant;
import io.bdmc.modules.sys.mapper.SysMenuMapper;
import io.bdmc.modules.sys.mapper.SysUserMapper;
import io.bdmc.modules.sys.mapper.SysUserTokenMapper;
import io.bdmc.modules.sys.entity.SysMenu;
import io.bdmc.modules.sys.entity.SysUser;
import io.bdmc.modules.sys.entity.SysUserToken;
import io.bdmc.modules.sys.service.ShiroService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

@Service
public class ShiroServiceImpl implements ShiroService {
    @Autowired
    private SysMenuMapper menuMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysUserTokenMapper sysUserTokenMapper;

    @Override
    public Set<String> getUserPermissions(long userId) {
        List<String> permsList;

        // 系统管理员，拥有最高权限
        if (userId == Constant.SUPER_ADMIN) {
            List<SysMenu> menuList = menuMapper.queryList();
            permsList = new ArrayList<>(menuList.size());
            for (SysMenu menu : menuList) {
                permsList.add(menu.getPerms());
            }
        } else {
            permsList = userMapper.queryAllPerms(userId);
        }
        // 用户权限列表
        Set<String> permsSet = new HashSet<>();
        for (String perms : permsList) {
            if (StringUtils.isBlank(perms)) {
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

    @Override
    public SysUserToken queryByToken(String token) {
        QueryWrapper<SysUserToken> w1 = new QueryWrapper<>();
        w1.eq("token", token);
        return sysUserTokenMapper.selectOne(w1);
    }

    @Override
    public SysUser queryUser(Long userId) {
        return userMapper.queryObject(userId);
    }
}
